import 'package:common_utils/common_utils.dart'; // 时间（第三方库）
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jiang_yue/home/ProgressDialog.dart'; // 显示加载中模块
import 'package:jiang_yue/home/SelectTime.dart'; // 时间选择器组件
import 'package:jiang_yue/modal/User.dart'; // 用户数据模型
import 'package:jiang_yue/utils/cache/UserCache.dart';
import 'package:jiang_yue/utils/toast/TsUtils.dart';
import 'package:scoped_model/scoped_model.dart'; // 状态管理
import 'package:jiang_yue/home/Toast.dart';
import 'dart:async';
import 'package:jiang_yue/modal/Tages.dart'; // 标签数据模型
import 'package:jiang_yue/modal/Article.dart';

enum Action { OK, Cancel }

class PublishPost extends StatefulWidget {
  @override
  _PublishPostState createState() => _PublishPostState();
}

class _PublishPostState extends State<PublishPost> {
  TextEditingController joinController = TextEditingController(); // 参加人数控制器
  List<int> _selected = [];
  bool _isPublish = false;

  // 文章数据
  String _title = "";
  String _content = "";
  String _lastTime = DateUtil.getNowDateMs().toString();
  String _createTime = DateUtil.getNowDateMs().toString();
  int _typeIndex;
  int _joinNum = 0; // 参加的人数

  void saveDateTime(date) {
    setState(() {
      _lastTime = date;
    });
  }

  Future _openAlertDialog() async {
    final action = await showDialog(
        context: context,
        barrierDismissible: false, // 若设置为false用户不能点击空白部分来关闭对话框
        builder: (BuildContext context) {
          return ScopedModel(
              model: CounterModel(),
              child: AlertDialog(
                content: new StatefulBuilder(builder: (context, StateSetter setState) {
                  // 保证AlertDialog可以实时更新
                  return Container(
                    height: 300,
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text('本贴类型：'),
                          Wrap(
                            spacing: 8,
                            children: tags.map((item) {
                              return FilterChip(
                                avatar: item.icon,
                                label: item.content,
                                selected: _selected.contains(item.id),
                                onSelected: (value) {
                                  setState(() {
                                    if (_selected.contains(item.id)) {
                                      _selected.remove(item.id);
                                    } else {
                                      if (_selected.length == 0) {
                                        _selected.add(item.id);
                                      } else {
                                        Toast.show(context, '只能选择一种标签作为本帖标签');
                                      }
                                    }
                                  });
                                },
                              );
                            }).toList(),
                          ),
                          SizedBox(
                            height: 16,
                          ),
                          Row(
                            children: <Widget>[
                              Text('活动结束时间： '),
                              SelectTimeHome(
                                callback: (date) => saveDateTime(date),
                              ),
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Text('限定参加人数：'),
                              Expanded(
                                child: TextField(
                                  inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], //只允许输入数字
                                  controller: joinController,
                                  onChanged: (String value) {
                                    setState(() {
                                      _joinNum = int.parse(value);
                                    });
                                  },
                                  decoration: InputDecoration(
                                    contentPadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 5),
                                    isDense: true,
                                    border: const OutlineInputBorder(
                                      gapPadding: 0,
                                      borderRadius: const BorderRadius.all(Radius.circular(4)),
                                      borderSide: BorderSide(
                                        width: 1,
                                        style: BorderStyle.solid,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  );
                }),
                actions: <Widget>[
                  FlatButton(
                    child: Text('取消'),
                    onPressed: () {
                      Navigator.pop(context, Action.Cancel);
                    },
                  ),
                  ScopedModelDescendant<CounterModel>(
                    builder: (context, _, model) => FlatButton(
                      child: Text('发布'),
                      onPressed: () {
                        // 如果未选择本帖类型时，提示错误信息
                        if (_selected.length == 0) {
                          Toast.show(context, '未选择本贴类型');
                          return;
                        }
                        setState(() {
                          _isPublish = true;
                          _typeIndex = _selected[0];
                        });

                        model.addArticle(
                          title: _title,
                          content: _content,
                          typeIndex: _typeIndex,
                          lastTime: _lastTime,
                          createTime: _createTime,
                          joinNum: _joinNum,
                        );
                        Navigator.pop(context, Action.OK);
                      },
                    ),
                  )
                ],
              ));
        });

    switch (action) {
      case Action.OK:
        if (_lastTime == null) {
          break;
        }
        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModel(
        model: CounterModel(),
        child: Scaffold(
          backgroundColor: Colors.grey[200],
          appBar: AppBar(
            title: Text('发布帖子'),
            actions: <Widget>[
              ScopedModelDescendant<CounterModel>(
                  builder: (context, _, model) => Padding(
                      child: GestureDetector(
                        child: Text('下一步',
                            style: TextStyle(
                                fontSize: 20,
                                color: (((model.title.length != 0 || _title.length != 0) &&
                                        (model.content.length != 0 || _content.length != 0))
                                    ? Colors.white
                                    : Colors.black.withOpacity(0.2)))),
                        onTap: () {
                          setState(() {
                            _title = model.title;
                            _content = model.content;
                          });
                          // TODO: 获取用户昵称
                          bool status = (_title.length != 0 && _content.length != 0);
                          if (status) {
                            _openAlertDialog();
                          }
                        },
                      ),
                      padding: EdgeInsets.only(top: 12, right: 20)))
            ],
          ),
          body: PublishPostHome(isPublish: _isPublish),
        ));
  }
}

class PublishPostHome extends StatefulWidget {
  final bool isPublish;
  PublishPostHome({
    Key key,
    @required bool this.isPublish,
  }) : super(key: key);
  @override
  _PublishPostHomeState createState() => _PublishPostHomeState();
}

class _PublishPostHomeState extends State<PublishPostHome> {
  TextEditingController titleController = TextEditingController(); // 标题控制器
  TextEditingController contentController = TextEditingController(); // 内容控制器
  bool _loading = false;
  bool _isPublish = false;
  int _count = 0;

  Future<Null> _onRefresh() async {
    setState(() {
      _loading = !_loading;
    });
    await Future.delayed(Duration(seconds: 3), () {
      setState(() {
        _loading = !_loading;
        _isPublish = false;
        Toast.show(context, "发布成功");
        Navigator.pop(context);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    setState(() {
      _isPublish = widget.isPublish;
    });
    if (_isPublish && (_count == 0)) {
      _onRefresh();
      setState(() {
        _count += 1;
      });
    }
    return Stack(
      children: <Widget>[
        ListView(
          children: <Widget>[
            ScopedModelDescendant<CounterModel>(
              builder: (context, _, model) => TextField(
                controller: titleController,
                onChanged: (String title) {
                  model.transform(data: title, type: 'title');
                },
                decoration: InputDecoration(
                  hintText: '标题',
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  isDense: true,
                  border: const OutlineInputBorder(
                    gapPadding: 0,
                    borderRadius: const BorderRadius.all(Radius.circular(4)),
                    borderSide: BorderSide(
                      width: 0,
                      style: BorderStyle.none,
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 30,
            ),
            ScopedModelDescendant<CounterModel>(
              builder: (context, _, model) => TextField(
                keyboardType: TextInputType.multiline,
                maxLines: 50,
                minLines: 28,
                controller: contentController,
                onChanged: (String content) {
                  model.transform(data: content, type: 'content');
                },
                decoration: InputDecoration(
                  hintText: '内容',
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  isDense: true,
                  border: const OutlineInputBorder(
                    gapPadding: 0,
                    borderRadius: const BorderRadius.all(Radius.circular(4)),
                    borderSide: BorderSide(
                      width: 0,
                      style: BorderStyle.none,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
        ProgressDialog(loading: _loading, child: Container()),
      ],
    );
  }
}

// 状态管理组件
class CounterModel extends Model {
  String _title = "";
  String _content = "";
  bool _isPublish = false;

  String get title => _title;
  String get content => _content;
  bool get isPublish => _isPublish;

  void transform({String data, @required String type}) {
    switch (type) {
      case 'title':
        _title = data;
        break;
      case 'content':
        _content = data;
        break;
      case 'publish':
        if (data == 'true') {
          _isPublish = true;
        }
        break;
      default:
    }
    notifyListeners();
  }

  void addArticle(
      {String title, String content, int typeIndex, String createTime, String lastTime, int joinNum}) async {
    Response response;
    response = await Dio().post("http://47.93.201.127:8080/jiangyue/publishPost", data: {
      "userID": userInfo[0].id,
      "title": title,
      "content": content,
      "tagID": typeIndex,
      "lastTime": int.parse(lastTime),
      "limitJoinNum": joinNum
    });

    if (response.data['success']) {
      // TsUtils.showShort('发布成功');
    } else {
      print('报错： PublishPost（发布帖子）');
    }
    notifyListeners();
  }
}
